import React, { useState } from 'react'

import { Form, ImageUploader, Input, List, NavBar, Picker, TextArea, Toast } from 'antd-mobile'

import styles from './index.module.css'
import HousePackage from '../../../components/HousePackage'

import { API } from '../../../utils'

const floorData = [
  [
    { label: '高楼层', value: 'FLOOR|1' },
    { label: '中楼层', value: 'FLOOR|2' },
    { label: '低楼层', value: 'FLOOR|3' }
  ]
]
const roomTypeData = [
  [
    { label: '一室', value: 'ROOM|d4a692e4-a177-37fd' },
    { label: '二室', value: 'ROOM|d1a00384-5801-d5cd' },
    { label: '三室', value: 'ROOM|20903ae0-c7bc-f2e2' },
    { label: '四室', value: 'ROOM|ce2a5daa-811d-2f49' },
    { label: '四室+', value: 'ROOM|2731c38c-5b19-ff7f' }
  ]
]
const orientedData = [
  [
    { label: '东', value: 'ORIEN|141b98bf-1ad0-11e3' },
    { label: '西', value: 'ORIEN|103fb3aa-e8b4-de0e' },
    { label: '南', value: 'ORIEN|61e99445-e95e-7f37' },
    { label: '北', value: 'ORIEN|caa6f80b-b764-c2df' },
    { label: '东南', value: 'ORIEN|dfb1b36b-e0d1-0977' },
    { label: '东北', value: 'ORIEN|67ac2205-7e0f-c057' },
    { label: '西南', value: 'ORIEN|2354e89e-3918-9cef' },
    { label: '西北', value: 'ORIEN|80795f1a-e32f-feb9' }
  ]
]

export default function RentAdd({ history, location }) {
  // 选择器显示隐藏
  const [floorVisible, setFloorVisible] = useState(false)
  const [roomTypeVisible, setRoomTypeVisible] = useState(false)
  const [orientedVisible, setOrientedVisible] = useState(false)

  const commun = { name: '', id: '' }
  const { state } = location
  if (state) {
    // 有小区数据，存储到状态中
    commun.name = state.name
    commun.id = state.id
  }

  // 小区的名称和id
  const [community, setCommunity] = useState(commun)
  // 表单数据
  const [formData, setFormData] = useState({
    title: '',
    description: '',
    oriented: '',
    supporting: '',
    price: '',
    roomType: '',
    size: '',
    floor: ''
  })
  // 选中的楼层、房型、朝向label
  const [selectLabel, setSelectLabel] = useState({
    floor: '',
    roomType: '',
    oriented: ''
  })
  // 临时文件路径
  const [tempSlides, setTempSlides] = useState([])

  // 获取表单数据
  function getValue(name, value) {
    setFormData({ ...formData, [name]: value })
  }

  function changePickerLabel(name, value) {
    // 判断是否有选择器的数据
    let label = ''
    if (name === 'roomType') {
      label = roomTypeData[0].find(item => item.value === value).label
      setSelectLabel({ ...selectLabel, [name]: label })
    } else if (name === 'floor') {
      label = floorData[0].find(item => item.value === value).label
      setSelectLabel({ ...selectLabel, [name]: label })
    } else if (name === 'oriented') {
      label = orientedData[0].find(item => item.value === value).label
      setSelectLabel({ ...selectLabel, [name]: label })
    }
  }

  function pickerCancel(name) {
    // 对应项置空
    setFormData({ ...formData, [name]: '' })
    // 对应项label置空
    setSelectLabel({ ...selectLabel, [name]: '' })
  }

  // 获取房屋配置数据
  function handleSupporting(selected) {
    setFormData({ ...formData, supporting: selected.join('|') })
  }

  // 获取房屋图片
  function handleHouseImg(files) {
    return {
      file: files,
      url: URL.createObjectURL(files)
    }
  }

  // 取消按钮
  function onCancel() {}

  // 提交表单
  async function addHouse() {
    // 判断价格和房型是否为空
    if (formData.price === '') return Toast.show({ content: '请输入价格' })
    if (formData.size === '') return Toast.show({ content: '请输入房屋面积' })

    let houseImg = ''
    if (tempSlides.length > 0) {
      // 已经有上传图片
      const form = new FormData()
      tempSlides.forEach(item => form.append('file', item.file))
      const { data: res } = await API.post('/houses/image', form, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })
      houseImg = res.body.join('|')
    }

    // 发布房源
    const { data: res } = await API.post('/user/houses', {
      ...formData,
      community: community.id,
      houseImg
    })
    // 发布失败
    if (res.status !== 200)
      return Toast.show({ icon: 'fail', content: '服务器偷懒了，请稍后再试~' })
    // 发布成功
    Toast.show({
      icon: 'success',
      content: '发布成功',
      afterClose() {
        history.push('/rent')
      }
    })
  }

  return (
    <div className={styles.root}>
      <NavBar onBack={() => history.go(-1)}>发布房源</NavBar>

      <List header="房屋信息">
        {/* 小区名称 */}
        <List.Item
          extra={community.name || '请输入小区名称'}
          clickable
          onClick={() => history.push('/rent/search')}
        >
          小区名称
        </List.Item>

        <Form layout="horizontal">
          {/* 租金 */}
          <Form.Item label="每月租金" extra="￥/月">
            <Input
              type="number"
              placeholder="请输入每月租金"
              onChange={val => getValue('price', val)}
            />
          </Form.Item>
          {/* 建设面积 */}
          <Form.Item label="建筑面积" extra="㎡">
            <Input
              type="number"
              placeholder="请输入建筑面积"
              onChange={val => getValue('size', val)}
            />
          </Form.Item>
        </Form>

        {/* 所在楼层 */}
        <Picker
          columns={roomTypeData}
          visible={roomTypeVisible}
          onClose={() => setRoomTypeVisible(false)}
          onSelect={val => getValue('roomType', val[0])}
          onConfirm={val => changePickerLabel('roomType', val[0])}
          onCancel={val => pickerCancel('roomType')}
        >
          {() => (
            <List.Item
              arrow
              extra={selectLabel.roomType || '请选择'}
              onClick={() => setRoomTypeVisible(true)}
            >
              所在楼层
            </List.Item>
          )}
        </Picker>

        {/* 户型 */}
        <Picker
          columns={floorData}
          visible={floorVisible}
          onClose={() => setFloorVisible(false)}
          onSelect={val => getValue('floor', val[0])}
          onConfirm={val => changePickerLabel('floor', val[0])}
          onCancel={val => pickerCancel('floor')}
        >
          {() => (
            <List.Item
              arrow
              extra={selectLabel.floor || '请选择'}
              onClick={() => setFloorVisible(true)}
            >
              户&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;型
            </List.Item>
          )}
        </Picker>

        {/* 朝向 */}
        <Picker
          columns={orientedData}
          visible={orientedVisible}
          onClose={() => setOrientedVisible(false)}
          onSelect={val => getValue('oriented', val[0])}
          onConfirm={val => changePickerLabel('oriented', val[0])}
          onCancel={val => pickerCancel('oriented')}
        >
          {() => (
            <List.Item
              arrow
              extra={selectLabel.oriented || '请选择'}
              onClick={() => setOrientedVisible(true)}
            >
              朝&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;向
            </List.Item>
          )}
        </Picker>

        {/* 房屋标题 */}
        <List.Item title="房屋标题">
          <Input
            placeholder="请输入房屋标题（例如：合租 小区名 3室 2000元）"
            onChange={val => getValue('title', val)}
          />
        </List.Item>

        {/* 房屋图像 */}
        <List.Item title="房屋图像">
          <ImageUploader
            multiple
            value={tempSlides}
            onChange={setTempSlides}
            upload={handleHouseImg}
          />
        </List.Item>

        {/* 房屋配置 */}
        <List.Item title="房屋配置">
          <HousePackage select onSelect={handleSupporting} />
        </List.Item>

        {/* 房屋描述 */}
        <List.Item title="房屋描述" className={styles.desc}>
          <TextArea
            placeholder="请输入房屋描述信息"
            rows={5}
            onChange={val => getValue('description', val)}
          />
        </List.Item>
      </List>

      {/* 底部按钮 */}
      <div className={styles.btns}>
        <span className={[styles.btn, styles.cancel].join(' ')} onClick={onCancel}>
          取消
        </span>
        <span className={[styles.btn, styles.ok].join(' ')} onClick={addHouse}>
          提交
        </span>
      </div>
    </div>
  )
}
